package com.sghy.xcxservice.common;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.SimplifiedObjectMeta;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class STS {

    public static JSONObject sts() {
        //构建一个阿里云客户端，用于发起请求。sts用户
        //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5t6Gxi4f58dHzURuNTe8",
                "nWb5QhLChpAPtSJGLvY3XKdHol7CM8");
        IAcsClient client = new DefaultAcsClient(profile);
        //构造请求，设置参数。关于参数含义和设置方法，请参见API参考。
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn("acs:ram::1777792904252976:role/sts");
        request.setRoleSessionName("client1");
        //设置token有效期，可选参数，默认3600秒。
        request.setDurationSeconds(3600L);

        //发起请求，并得到响应。
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            JSONObject info = JSONObject.parseObject(new Gson().toJson(response.getCredentials()));
            //utc格式的世界标准时间转成北京时间；
            info.put("expiration", utcToTeijing(info.getDate("expiration")));
            return info;
        } catch (ServerException e) {
            e.printStackTrace();
            return new JSONObject();
        } catch (ClientException e) {
            return JSONObject.parseObject(String.valueOf(e));
        }

    }
    
    public static String utcToTeijing(Date utcDate) {
        // 创建SimpleDateFormat对象，设置时区为北京时间
        SimpleDateFormat beijingSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        beijingSdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 时区设置为北京
        // 格式化Date对象为北京时间字符串
        return beijingSdf.format(utcDate);
    }
}

